"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 数据库系统
Case Name   : TPCC执行过程中，多次执行gs_om stop start查询主备数据库状态（DTS2020060103098）
Create At   : 2020/07/20
@zou_jialiang0505328114
Description :
    1.启动主备数据库，判断数据库状态；
    2.运行tpcc；
    3.运行tpcc期间多次执行数据库重启；
Expect      :
    1.启动主备数据库，判断数据库状态；
    2.运行tpcc；
    3.运行tpcc期间多次执行数据库重启；
History     :
    modified：2021-3-11 by 5328113;修改tpcc断言；修改重启循环次数；
"""

import unittest

from testcase.utils.ComThread import ComThread
from testcase.utils.Common import Common
from testcase.utils.CommonSH import *
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from yat.test import Node
from yat.test import macro


class Deletaduit(unittest.TestCase):
    nodes_tuple = ('PrimaryDbUser', 'Standby1DbUser', 'Standby2DbUser')

    @RestartDbCluster(*nodes_tuple)
    def setUp(self):
        self.log = Logger()
        self.log.info('----Opengauss_Reliability_Dbsys_Case157.py start----')
        self.pri_root = Node(node='PrimaryRoot')
        self.pri_dbuser = Node(node='PrimaryDbUser')
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.com = Common()
        self.Constant = Constant()

    def test_startdb(self):
        self.log.info('----运行tpcc----')
        tpcc_thread = ComThread(self.com.startTPCC,
                                args=(self.pri_root, macro.TPCC_PATH,))
        tpcc_thread.setDaemon(True)
        tpcc_thread.start()

        time.sleep(5)

        self.log.info('----运行tpcc期间多次执行数据库重启----')
        for i in range(10):
            is_stopped = self.pri_sh.stopDbCluster()
            self.assertTrue(is_stopped)
            is_started = self.pri_sh.startDbCluster()
            self.assertTrue(is_started)

        db_status = self.pri_sh.getDbClusterStatus('status')
        self.assertTrue(db_status)

        tpcc_thread.join(int(macro.TPCC_RUN_MAX_TIME) * 2)
        tpcc_result = tpcc_thread.get_result()
        self.log.info(tpcc_result)
        error_flags = ('error', 'ERROR', 'FATAL', 'connection attempt failed')
        if self.Constant.TPCC_SUCCESS_MSG in tpcc_result:
            self.assertTrue(any(err in tpcc_result for err in error_flags))
        else:
            self.assertNotIn(self.Constant.TPCC_SUCCESS_MSG, tpcc_result)

    def tearDown(self):
        self.log.info('----reliability_dbsys157.py finish----')
